package lium.lbs.lbsim.activity

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.buz.hjcdriver.bean.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jakewharton.rxbinding2.widget.RxTextView
import com.lmlibrary.Constants
import com.lmlibrary.bean.ResponseBean
import com.lzy.okgo.model.Response
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_choose_member.*
import kotlinx.android.synthetic.main.rc_toolbar_choose.*
import lium.lbs.lbsim.R
import lium.lbs.lbsim.adapter.ChooseFriendListtsetgmAddAdapter
import lium.lbs.lbsim.fragments.FriendListFragment
import lium.lbs.lbsim.jgchat.application.GJApp
import lium.lbs.lbsim.utils.*
import lium.lbs.lbsim.utils.callbck.DialogCallback
import java.util.HashMap
import java.util.concurrent.TimeUnit

class setGroupMagemenAddActivity : BaseActivity(), BaseQuickAdapter.OnItemClickListener {
    var myGroupId: String? = null
    var jgGroupId: String? = null
    var type: Int = 0
    var myTitle: String? = null
    lateinit var adapter: ChooseFriendListtsetgmAddAdapter
    private val listData: ArrayList<FriendsChooseResultModel> = arrayListOf()
    var friendAdapterList = arrayListOf<FriendsChooseResultModel>()
    internal var dialog: IAlertDialog? = null
    var pageNo: Int = 1
    /**
     * 汉字转换成拼音的类
     */
    private var characterParser: CharacterParser? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_forbidden_words
    }

    override fun initView(savedInstanceState: Bundle?) {
        myGroupId = intent.getStringExtra(GJApp.MY_GROUP_ID)
        jgGroupId = intent.getStringExtra(GJApp.GROUP_ID)
        right_text.visibility = View.GONE
        type = intent.getIntExtra("type", 0);
        myTitle = intent.getStringExtra("title")
        setTitleWithBack(myTitle)
        characterParser = CharacterParser.getInstance()
        adapter = ChooseFriendListtsetgmAddAdapter(listData)
        recyclerView.adapter = adapter
        adapter.disableLoadMoreIfNotFullPage(recyclerView) //关闭BRAVE的自动加载功能 改成 refreshLayout的上拉加载
        adapter.onItemClickListener = this
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        recyclerView.addItemDecoration(PinnedHeaderItemDecoration())
        addOnClickListeners(
            R.id.right_text
        )
        mSidBar.setTextView(slide_dialog)
        mSidBar.setOnTouchingLetterChangedListener {
            //该字母首次出现的位置
            var position = 0
            for ((index, friend) in adapter.data.withIndex()) {
                if (TextUtils.equals(friend.letters, it.toUpperCase())) { //转为大写后 判断是否相同
                    position = index
                    if ("#" == it) {
                        position = -1 //不处理#
                    }
                    if ("A" == it) {
                        position = 1 //不处理#
                    }

                    break
                }
            }
            if (position != -1 && position != 0) {
                recyclerView.scrollToPosition(position)
                var mLayoutManager = recyclerView.layoutManager as LinearLayoutManager
                mLayoutManager.scrollToPositionWithOffset(position, 0)
            }
        }

        addDisposable(
            RxTextView.textChanges(search_myfriends)
                .debounce(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(CharSequence::toString)
                .subscribe {
                    getDataList()
                })
    }

    override fun getNetWorkData() {
    }

    companion object {
        fun newInstance(): FriendListFragment {
            return FriendListFragment()
        }
    }

    fun getDataList() {
        val param = HashMap<String, String>()
        param["memberId"] = SpUtils.getInstance().get(Constants.memberId, "") as String
        param["groupId"] = myGroupId.toString()
        param["pageNo"] = pageNo.toString()
        param["pageSize"] = "60"


        postData(
            "/group/groupMember",
            param,
            object : DialogCallback<ResponseBean<GroupJYResultModel>>(this) {
                override fun onSuccess(response: Response<ResponseBean<GroupJYResultModel>>) {
                    setDataList(response.body().data.memberList)
                }
            })


    }


    fun setDataList(list: List<JYMemberListBean>) {
        friendAdapterList.clear()

        if (list != null && !list.isEmpty()) {
            show_no_friend.visibility = View.GONE
            for (friend in list) {
                val pinyin = characterParser!!.getSelling(
                    if (TextUtils.isEmpty(friend.gcard)) {
                        friend.nickName
                    } else {
                        friend.gcard
                    }
                )
                val sortString = pinyin.substring(0, 1).toUpperCase()
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]".toRegex())) {
                    friend.letters = sortString.toUpperCase()
                } else {
                    friend.letters = "#"
                }
            }
            //list.sortBy { it.letters }

            for ((index, bean) in list.withIndex()) {
                if ("3".equals(bean.type)) {
                    if (index == 0) {
                        friendAdapterList.add(
                            0,
                            FriendsChooseResultModel("", "", "", false, bean.letters, FriendsModel.ITEM_TYPE_SETION)
                        )
                        friendAdapterList.add(
                            FriendsChooseResultModel(
                                bean.memberId,
                                if (TextUtils.isEmpty(bean.gcard)) {
                                    bean.nickName
                                } else {
                                    bean.gcard
                                },
                                if (TextUtils.isEmpty(bean.headImage)) {
                                    ""
                                } else {
                                    bean.headImage
                                },
                                if ("0".equals(bean.isBanned)) {
                                    false
                                } else {
                                    true
                                },
                                bean.letters,
                                bean.orderMultiType
                            )
                        )
                    } else {
                        if (TextUtils.equals(list[index - 1].letters, bean.letters)) { //判断上一个item缩写字母和当前的 是否一样
                            friendAdapterList.add(
                                FriendsChooseResultModel(
                                    bean.memberId,
                                    if (TextUtils.isEmpty(bean.gcard)) {
                                        bean.nickName
                                    } else {
                                        bean.gcard
                                    },
                                    if (TextUtils.isEmpty(bean.headImage)) {
                                        ""
                                    } else {
                                        bean.headImage
                                    },
                                    if ("0".equals(bean.isBanned)) {
                                        false
                                    } else {
                                        true
                                    },
                                    bean.letters,
                                    bean.orderMultiType
                                )
                            )
                        } else {
                            friendAdapterList.add(
                                FriendsChooseResultModel(
                                    "",
                                    "",
                                    "",
                                    if ("0".equals(bean.isBanned)) {
                                        false
                                    } else {
                                        true
                                    },
                                    bean.letters,
                                    FriendsModel.ITEM_TYPE_SETION
                                )
                            )
                            friendAdapterList.add(
                                FriendsChooseResultModel(
                                    bean.memberId,
                                    if (TextUtils.isEmpty(bean.gcard)) {
                                        bean.nickName
                                    } else {
                                        bean.gcard
                                    },
                                    if (TextUtils.isEmpty(bean.headImage)) {
                                        ""
                                    } else {
                                        bean.headImage
                                    },
                                    if ("0".equals(bean.isBanned)) {
                                        false
                                    } else {
                                        true
                                    },
                                    bean.letters,
                                    bean.orderMultiType
                                )
                            )
                        }
                    }
                }
            }


        } else {
            show_no_friend.visibility = View.VISIBLE
        }
        adapter.data.clear()
        adapter.data.addAll(friendAdapterList)
        adapter.loadMoreComplete()
        adapter.notifyDataSetChanged()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        if (type == 0) {
            getDataListMageman((adapter!!.data.get(position) as FriendsChooseResultModel).friendId)
        }

    }

    fun getDataListMageman(bannedMemberId: String) {
        val param = HashMap<String, String>()
        param["memberId"] = SpUtils.getInstance().get(Constants.memberId, "") as String
        param["adminMemberId"] = bannedMemberId
        param["groupId"] = myGroupId.toString()

        postData(
            "/group/setGroupAdmin",
            param,
            object : DialogCallback<ResponseBean<GroupJYResultModel>>(this) {
                override fun onSuccess(response: Response<ResponseBean<GroupJYResultModel>>) {
                    setDataList(response.body().msg)
                }
            })


    }

    fun setDataList(msg: String) {
        ToastUtils.showLongToast(msg)
        setResult(200)
        getDataList()
    }
}
